package com.youxin.other.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.admin.pay.client.req.AgentStaticSearch;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TPage;
import com.youxin.exception.SystemException;
import com.youxin.other.report.mapper.AgentStaticMapper;
import com.youxin.other.report.model.AgentStatic;
import com.youxin.other.report.service.AgentStaticService;
import com.youxin.other.report.service.rpc.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * description: ReportService <br>
 * date: 2020/3/6 11:01 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class AgentStaticServiceImpl extends ServiceImpl<AgentStaticMapper, AgentStatic> implements AgentStaticService {

    private static Logger logger = LoggerFactory.getLogger(AgentStaticServiceImpl.class);

    @Resource
    private RpcService rpcService;

    private ExecutorService executor = Executors.newSingleThreadExecutor();
    @Override
    public void staticAgentData(AgentStaticSearch agentStaticSearch) {
        executor.execute(()->{
            asyncStaticAgentData(agentStaticSearch);
        });
    }

    @Override
    public TPage<AgentStatic> listAgentStatics(AgentStaticSearch search) {
        LambdaQueryWrapper<AgentStatic> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(search.getAgentNo())) {
            queryWrapper.eq(AgentStatic::getAgentNo, search.getAgentNo());
        }
        if (!StringUtils.isEmpty(search.getStartTime())) {
            queryWrapper.ge(AgentStatic::getStaticTime, search.getStartTime());
        }
        if (!StringUtils.isEmpty(search.getStartTime())) {
            queryWrapper.le(AgentStatic::getStaticTime, search.getEndTime());
        }
        queryWrapper.orderByDesc(AgentStatic::getStaticTime);
        IPage<AgentStatic> page = page(new Page<>(search.getCurrentPage(), search.getShowCount()), queryWrapper);
        return TPage.page(page.getRecords(),page.getTotal());
    }

    private void asyncStaticAgentData(AgentStaticSearch agentStaticSearch){
        if (StringUtils.isEmpty(agentStaticSearch.getStartTime()) || StringUtils.isEmpty(agentStaticSearch.getEndTime())) {
            logger.error("请选择开始时间与结束时间");
            throw new SystemException(BaseResultCode.COMMON_FAIL, "请选择开始时间与结束时间");
        }
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime startTime = LocalDate.parse(agentStaticSearch.getStartTime(), dateFormatter).atStartOfDay();
        LocalDateTime endTime = LocalDate.parse(agentStaticSearch.getEndTime(), dateFormatter).plusDays(1).atStartOfDay();
        LambdaQueryWrapper<AgentStatic> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(agentStaticSearch.getAgentNo())) {
            queryWrapper.eq(AgentStatic::getAgentNo, agentStaticSearch.getAgentNo());
        }
        queryWrapper.ge(AgentStatic::getStaticTime, startTime).lt(AgentStatic::getStaticTime, endTime);
        remove(queryWrapper);
        List<AgentStatic> agentStatics = new ArrayList<>();
        while (startTime.isBefore(endTime)) {
            AgentStaticSearch param = new AgentStaticSearch();
            param.setAgentNo(agentStaticSearch.getAgentNo());
            param.setStartTime(startTime.format(dateTimeFormatter));
            param.setEndTime(startTime.plusDays(1).toLocalDate().atStartOfDay().format(dateTimeFormatter));
            List<AgentStatic> dayStatics = rpcService.staticAgentTransaction(param);
            if (!CollectionUtils.isEmpty(dayStatics)) {
                LocalDateTime staticTime = startTime.toLocalDate().atStartOfDay();
                dayStatics.stream().forEach(item -> {
                    item.setStaticTime(staticTime);
                });
                agentStatics.addAll(dayStatics);
            }
            startTime = startTime.plusDays(1);
        }
        if (!CollectionUtils.isEmpty(agentStatics)) {
            saveBatch(agentStatics);
        }
    }

}
